//
//  CCSlider.swift
//  Key2
//
//  Created by liujianlong on 2023/6/20.
//

import UIKit
import SnapKit
#if canImport(TCC_String)
import TCC_String
#endif
#if canImport(TCC_Extension)
import TCC_Extension
#endif
#if canImport(TCC_View)
import TCC_View
#endif
class CCSlider: UIView {
    var slider_edges = UIEdgeInsets(top: 7, left: 10, bottom: 7, right: 10)
    private(set) var slider : UISlider!
    private(set) var progresss_layer : CAShapeLayer!
    private(set) var color_layer : CAGradientLayer!
    private var displayLink:CADisplayLink!
    var block:((_ value:CGFloat)->Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        initUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func initUI(){
        self.bgHexColor = "#303143"
        ///
        slider = UISlider()
        slider.minimumTrackTintColor = .clear
        slider.maximumTrackTintColor = .clear
        slider.thumbTintColor = "#FF5733".color()
        slider.maximumValue = 10
        slider.minimumValue = 1
        slider.value = 1
        slider.isContinuous = false
        slider.addTarget(self, action: #selector(actionForSlider), for:.valueChanged)
        ///使用 CADisplayLink 可以确保你的代码在每一帧都得到执行，从而避免动画延迟问题。 CADisplayLink 对象添加到主运行循环中
        displayLink = CADisplayLink(target:self, selector: #selector(updateStrokeEnd))
        displayLink.add(to: .main, forMode: .default)
        self.addSubview(slider)
        slider.snp.makeConstraints { make in
            make.top.equalToSuperview().inset(slider_edges.top)
            make.left.equalToSuperview().inset(slider_edges.left)
            make.right.equalToSuperview().inset(slider_edges.right)
            make.bottom.equalToSuperview().inset(slider_edges.bottom)
        }
        
        ///自定义进度条layer
        self.layoutIfNeeded()
        let path = UIBezierPath()
        path.move(to: CGPoint(x: 6, y: slider.bounds.height / 2))
        path.addLine(to: CGPoint(x: slider.bounds.width - 15, y: slider.bounds.height / 2))
        progresss_layer = CAShapeLayer.init()
        progresss_layer.frame = slider.bounds
        progresss_layer.lineWidth = 28
        progresss_layer.fillColor = UIColor.clear.cgColor
        progresss_layer.strokeColor = UIColor.red.cgColor
        progresss_layer.path = path.cgPath
        progresss_layer.strokeEnd = 0
        progresss_layer.lineCap = .round
        
        ///渐变色
        color_layer = CAGradientLayer()
        color_layer.frame = slider.bounds
        color_layer.colors = ["#00BAAD".color().cgColor,"#FF5733".color().cgColor]
        color_layer.startPoint = CGPoint(x: 0, y: 0)
        color_layer.endPoint = CGPoint(x: 1, y: 0)
        color_layer.cornerRadius = 14
        color_layer.mask = progresss_layer
        slider.layer.insertSublayer(color_layer, at: 0)
    }
    
    var value:Int=0{
        didSet{
            slider.value = Float(value)
            actionForSlider(slider)
        }
    }
    @objc func actionForSlider(_ sender:UISlider){
        block?(CGFloat(sender.value))
        updateStrokeEnd()
    }
    
    @objc func updateStrokeEnd(){
        CATransaction.begin()
        CATransaction.setAnimationDuration(0) // 设置动画持续时间为 0.1 秒
        progresss_layer.strokeEnd = CGFloat((slider.value - slider.minimumValue) / (slider.maximumValue - slider.minimumValue))
        CATransaction.commit()
    }
    
    ///用完，必须调用这个
    func invalidate(){
        displayLink.invalidate()
        displayLink = nil
    }
    deinit{
        print("")
    }
    
}

//MARK: - 方法2  （不带渐变色）
//import UIKit
//import TCCKit
//enum DSliderDirection{
//    case vertical
//    case horizontal
//}
//
//@objc protocol DSliderDelgate {
//    func valueForChange(_ sender:DSlider)
//    @objc optional func valueForChangeEnd(_ sender:DSlider)
//}
//private var _temp_value : CGFloat = 0.0
//class DSlider: UIView {
//    var delegate : DSliderDelgate?
//    var minValue : CGFloat = 0.0
//    var maxValue : CGFloat = 1.0
//    var currentValue : CGFloat = 0.0{
//        didSet{
//            animateBarHeight(currentValue)
//        }
//    }
//    var thumImg : UIImageView!
//    private var shapeView : UIView!
//    private var shape : CAShapeLayer!
//    private var colorLayer : CAGradientLayer!
//    private var didAnimation = false
//    private var displayLink: CADisplayLink?
//    override init(frame: CGRect) {
//        super.init(frame: frame)
//        initUI()
//    }
//    
//    required init?(coder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
//    }
//    
//    func initUI(){
//        translatesAutoresizingMaskIntoConstraints = false
//        
//        thumImg = UIImageView()
//        thumImg.contentMode = .scaleAspectFill
//        
//        shape = CAShapeLayer()
//        // shape.fillColor = UIColor.clear.cgColor
//        shape.fillColor = HEX_BLUE.color().cgColor
//        
//        colorLayer = CAGradientLayer()
//        colorLayer.colors = [HEX_BLUE.color().cgColor, HEX_RED.color().cgColor]
//        
//        shapeView = UIView()
//        shapeView.backgroundColor = .clear
//        shapeView.isUserInteractionEnabled = false
//        shapeView.cornerRadius = 5
//        enable = true
//        
//        addSubview(shapeView)
//        shapeView.layer.addSublayer(shape)
//        shapeView.layer.addSublayer(colorLayer)
//        shapeView.addSubview(thumImg)
//        ///！！！！！这里一定要注意，要放在<shapeView.layer.addSublayer(colorLayer)>后面 ，否则colorLayer不会跟着shape形变
//        colorLayer.mask = shape
//        
//        
//        let pan2 = UIPanGestureRecognizer(target:self, action:#selector(actionForPan))
//        self.addGestureRecognizer(pan2)
//        direction = .vertical
//    }
//    
//    override func layoutSubviews() {
//        super.layoutSubviews()
//        if didAnimation {return}
//        animateBarHeight(currentValue)
//    }
//    
//    func setColors(_ colors:[UIColor]){
//        CATransaction.begin()
//        CATransaction.setDisableActions(true)
//        colorLayer.colors = colors.map{$0.cgColor}
//        CATransaction.commit()
//    }
//    
//    var direction : DSliderDirection = .vertical{
//        didSet{
//            switch direction{
//            case .vertical:
//                colorLayer.locations = [0,1]
//                colorLayer.startPoint = CGPoint(x: 0, y: 0)
//                colorLayer.endPoint = CGPoint(x: 1, y: 0)
//                thumImg.snp.remakeConstraints { make in
//                    make.width.equalTo(thumImg.snp.height)
//                    make.top.bottom.equalToSuperview().inset(0)
//                    make.left.equalToSuperview().offset(0)
//                }
//                shapeView.snp.remakeConstraints { make in
//                    make.left.right.equalToSuperview().inset(5)
//                    make.height.equalTo(10)
//                    make.centerY.equalToSuperview()
//                }
//                thumImg.layoutIfNeeded()
//            case .horizontal:
//                colorLayer.locations = [0,1]
//                colorLayer.startPoint = CGPoint(x: 0, y: 1)
//                colorLayer.endPoint = CGPoint(x: 0, y: 0)
//                thumImg.snp.remakeConstraints { make in
//                    make.width.equalTo(thumImg.snp.height)
//                    make.left.right.equalToSuperview().inset(0)
//                    make.bottom.equalToSuperview().offset(0)
//                }
//                shapeView.snp.remakeConstraints { make in
//                    make.top.bottom.equalToSuperview().inset(5)
//                    make.width.equalTo(10)
//                    make.centerX.equalToSuperview()
//                }
//                thumImg.layoutIfNeeded()
//            }
//        }
//    }
//    
//    var enable:Bool = true{
//        didSet{
//            shapeView.borderWidth = enable ? 1 : 0.5
//            shapeView.borderHexColor = enable ? HEX_BLACK : HEX_WHITE
//            shapeView.bgHexColor = enable ? HEX_BG : HEX_BG_DISABLE
//            setColors(enable ? [HEX_BLUE.color(), HEX_RED.color()] : [HEX_GRAY2.color(),HEX_GRAY2.color()])
//            isUserInteractionEnabled = enable
//        }
//    }
//    
//    @objc private func actionForPan(_ pan:UIPanGestureRecognizer){
//        let location = pan.location(in: shapeView)
//        let locationX = min(max(0, location.x), shapeView.bounds.width)
//        let locationY = min(max(0, location.y), shapeView.bounds.height)
//        let x = (locationX) / shapeView.bounds.width * (maxValue - minValue)
//        let y = (shapeView.bounds.height - locationY) / shapeView.bounds.height * (maxValue - minValue)
//        ///这个算法非常重要，可保证(min...max = -10...0) , (min...max = -10...10) ,(min...max = 0...10) 三种情况下，currentVaue都是正确的
//        _temp_value = minValue + (direction == .vertical ? x : y)
//        if pan.state == .ended{
//            displayLink?.invalidate()
//            displayLink = nil
//            currentValue = _temp_value
//            DispatchQueue.main.async {[weak self] in
//                self?.delegate?.valueForChangeEnd?(self ?? DSlider())
//            }
//        }else if pan.state == .began{
//            displayLink = CADisplayLink(target: self, selector: #selector(handleDisplayLink))
//            displayLink?.add(to: .main, forMode: .common)
//        }
//    }
//    
//    @objc private func handleDisplayLink() {
//        delegate?.valueForChange(self)
//        currentValue = _temp_value
//    }
//    
//    private func animateBarHeight(_ value:CGFloat) {
//        didAnimation = shapeView.bounds.width > 0
//        colorLayer.frame = shapeView.bounds
//        shape.frame = shapeView.bounds
//        ///因为max和min可能为负数，所以归一 化
//        let scale = CGFloat(value - minValue) / CGFloat(maxValue - minValue)
//        var oldPath : UIBezierPath!
//        var newPath : UIBezierPath!
//        switch direction {
//        case .vertical:
//            let offsetX = shape.bounds.width * scale
//            newPath = UIBezierPath(roundedRect:CGRect(x:0, y:0,
//                                                      width:offsetX + thumImg.bounds.width / 2.0, height:shape.frame.height),
//                                   byRoundingCorners:[.topLeft,.topRight,.bottomLeft,.bottomRight],
//                                   cornerRadii:CGSize(width:shape.bounds.height/2.0, height: shape.bounds.height/2.0))
//            
//            oldPath = UIBezierPath(roundedRect:CGRect(x:0, y: 0,
//                                                      width:shape.bounds.width, height: shape.bounds.height),
//                                   byRoundingCorners:[.topLeft,.topRight,.bottomLeft,.bottomRight],
//                                   cornerRadii:CGSize(width:shape.bounds.height/2.0, height:shape.bounds.height/2.0))
//            thumImg.snp.updateConstraints { make in
//                make.left.equalToSuperview().offset(min(offsetX, shapeView.bounds.width-thumImg.bounds.width))
//            }
//        case .horizontal:///竖直状态下，y轴滑动位移，下->上 = 小->大。而UIBezierPath画线的顶点的Y轴是，上->下 = 小->大。就不能直接使用上面的逻辑。
//            let offsetY = (shape.bounds.height - thumImg.bounds.height) * scale
//            let y = offsetY + thumImg.bounds.width / 2.0///实际上有用的滑动的点是thumimg的中心
//            newPath = UIBezierPath(roundedRect:CGRect(x:0, y:shape.bounds.height-y,
//                                                      width:shape.frame.width, height:y),
//                                   byRoundingCorners:[.topLeft,.topRight,.bottomLeft,.bottomRight],
//                                   cornerRadii:CGSize(width:shape.bounds.width/2, height: shape.bounds.width/2))
//            
//            oldPath = UIBezierPath(roundedRect:CGRect(x:0, y: shape.bounds.height,
//                                                      width:shape.bounds.width, height: 0),
//                                   byRoundingCorners:[.topLeft,.topRight,.bottomLeft,.bottomRight],
//                                   cornerRadii:CGSize(width:shape.bounds.width/2, height:shape.bounds.width/2))
//            thumImg.snp.updateConstraints { make in
//                make.bottom.equalToSuperview().offset(max(-offsetY, thumImg.bounds.height - shape.bounds.height))
//            }
//        }
//        
//        let animation = CABasicAnimation(keyPath: "path")
//        animation.fromValue = oldPath.cgPath
//        animation.toValue = newPath.cgPath
//        animation.duration = 0.001 // 动画持续时间，可以根据需要进行调整
//        animation.fillMode = .forwards
//        animation.isRemovedOnCompletion = false
//        shape.removeAnimation(forKey: "pathAnimation")
//        shape.add(animation, forKey: "pathAnimation")
//    }
//}
//
//
